package com.ysxsoft.wdg.ui.activity.my;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.response.HomeProductResponse;
import com.ysxsoft.wdg.bean.response.MyFenSiResponse;
import com.ysxsoft.wdg.bean.response.MyKanResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.KanWebViewActivity;
import com.ysxsoft.wdg.ui.activity.MainActivity;
import com.ysxsoft.wdg.ui.activity.my.partner.MyFsActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.statusbar.StatusBarUtil;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

public class KanActivity extends BaseActivity {
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_iv_r)
    ImageView titleIvR;
    @BindView(R.id.title_tv_r)
    TextView titleTvR;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.ll_refresh)
    LinearLayout llRefresh;
    private int page = 1;
    MyAdapter adapter;
    private HashMap<String, CountTimer> timerMap = new HashMap<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, KanActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_kan;
    }

    @Override
    protected void initData() {
        StatusBarUtil.setStatusBarTextColor(this, true);
        initStatusBar(topView, true);
        titleContent.setText("我的秒杀");
        titleFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setLayoutManager(new FastSpeedLinearLayoutManager(this));
        adapter = new MyAdapter(R.layout.item_kan_jia);
        recyclerview.setAdapter(adapter);
        multStatusView.showLoading();

        getList();
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getList();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                getList();
            }
        });
    }

    /**
     * 获取我的砍价
     */
    private void getList() {
        OkHttpUtils.post()
                .url(UrlHost.MY_KAN)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("page", page + "")
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    reset();
                    multStatusView.showError();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                reset();
                if (response != null) {
                    MyKanResponse myKanResponse = JsonUtils.parseByGson(response, MyKanResponse.class);
                    if (myKanResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(myKanResponse.getCode())) {
                        List<MyKanResponse.DataBean> list = myKanResponse.getData();
                        if (page == 1) {
                            multStatusView.showContent();
                            if (list != null && !list.isEmpty()) {
                            } else {
                                multStatusView.showEmpty();
                            }
                            systemTime = SystemClock.elapsedRealtime();//获取系统当前开机时间
                            adapter.setNewData(list);
                        } else {
                            adapter.addData(list);
                        }
                    }else{
                        if (page == 1) {
                            multStatusView.showEmpty();
                        }
                    }
                } else {
                    multStatusView.showError();
                }
            }
        });
    }

    private long systemTime;

    class MyAdapter extends BaseQuickAdapter<MyKanResponse.DataBean, BaseViewHolder> {

        @Override
        public void onViewRecycled(@NonNull BaseViewHolder holder) {
            super.onViewRecycled(holder);
            View view = holder.getView(R.id.h);//移除countDownTime
            if (view != null && view.getVisibility() == View.VISIBLE && view.getTag() != null) {
                CountTimer timer = (CountTimer) view.getTag();
                timer.cancel();
            }
        }

        public MyAdapter(int layoutResId) {
            super(layoutResId);
        }

        public void clear() {
            getData().clear();
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, MyKanResponse.DataBean item) {
            MyKanResponse.DataBean.DetailBean d = item.getDetail();
            LinearLayout timeLayout = helper.getView(R.id.timelayout);
            if (d != null) {
                Glide.with(mContext).load(d.getPic()).into((ImageView) helper.getView(R.id.image));
                helper.setText(R.id.name, d.getName());

                //按钮
                TextView btn = helper.getView(R.id.btn);

                //状态
                TextView description = helper.getView(R.id.description);
                if (item.getSta() == 1) {//1继续砍价2砍价成功3砍价失败
                    description.setVisibility(View.VISIBLE);
                    helper.setText(R.id.status, "还差" + item.getCa_money() + "元");
                    btn.setText("继续砍价");

                    TextView day = helper.getView(R.id.d);
                    TextView h = helper.getView(R.id.h);
                    TextView m = helper.getView(R.id.m);
                    TextView s = helper.getView(R.id.s);

                    String key = item.getOrderid() + "";
                    long t = SystemClock.elapsedRealtime() - systemTime;
                    long mss = item.getCa() * 1000;//时间
                    mss -= t;//总时间减去  已运行的时间
                    int interval = 1000;
                    CountTimer timer = new CountTimer(mss, interval);
                    timer.setTextView(day,h, m, s);
                    timerMap.put(key, timer);
                    timer.start();
                    helper.setTag(R.id.h, timer);
                    timeLayout.setVisibility(View.VISIBLE);
                } else if (item.getSta() == 3) {//砍价失败
                    description.setVisibility(View.GONE);
                    helper.setText(R.id.status, item.getStatus());
                    btn.setText("重砍一个");
                    timeLayout.setVisibility(View.INVISIBLE);

                } else if (item.getSta() == 2) {//砍价成功
                    description.setVisibility(View.GONE);
                    helper.setText(R.id.status, item.getStatus());
                    btn.setText("查看详情");
                    timeLayout.setVisibility(View.INVISIBLE);
                }
                btn.setOnClickListener(new OnKanClickListener(item));
            }
        }
    }

    private class OnKanClickListener implements View.OnClickListener {
        private MyKanResponse.DataBean p;

        public OnKanClickListener(MyKanResponse.DataBean p) {
            this.p = p;
        }

        @Override
        public void onClick(View v) {
            if (p.getSta() == 3) {
                Intent intent = new Intent(KanActivity.this, MainActivity.class);
                intent.putExtra("p", true);
                startActivity(intent);
            } else {
                KanWebViewActivity.start(KanActivity.this, UrlHost.BASE_URL+"/index.html#/bargainDetails?detailId=" + p.getOrderid());
            }
        }
    }

    private void reset() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh(true);
        }
        refreshLayout.finishLoadmore();
    }


    private class CountTimer extends CountDownTimer {
        private TextView textView0;
        private TextView textView1;
        private TextView textView2;
        private TextView textView3;

        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void setTextView(TextView textView0,TextView textView, TextView textView2, TextView textView3) {
            this.textView0 = textView0;
            this.textView1 = textView;
            this.textView2 = textView2;
            this.textView3 = textView3;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long s = (millisUntilFinished / 1000);
            long h = s / 3600;
            long m = (s - h * 3600) / 60;
            long ss = s % 60;
            textView0.setText(String.format("%02d", h/24));//天
            textView1.setText(String.format("%02d", h%24));//小时
            textView2.setText(String.format("%02d", m));//分钟
            textView3.setText(String.format("%02d", ss));//秒
        }

        @Override
        public void onFinish() {
            textView1.setText("00");
            textView2.setText("00");
            textView3.setText("00");
        }
    }

    private String ssToStr(long s) {
        long h = s / 3600;
        long m = (s - h * 3600) / 60;
        long ss = s % 60;
        String str = String.format("剩余%02d小时%02d分%02d秒", h, m, ss);
        return str;
    }
}

